package com.cam.test.wechat;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cam.framework.utils.RestResult;
import com.cam.test.wechat.utils.WechatUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test/gzh")
public class WechatGzhController {

    @GetMapping("/test")
    public void test() {
        List<HashMap> liveList = WechatUtils.getVideoLive();
        List<HashMap> liveNoticeList = WechatUtils.getVideoNoticeList();
        return;
    }

    public RestResult authorize(String code) {
        /*
        * 微信公众号授权流程
        * 第一步，首先在调用需要授权或登录的接口时跳转到微信公众号官方提供的https://open.weixin.qq.com/connect/oauth2/authorize页面，
        *   详细参数见微信官方文档
        * 第二步，用户在官方授权页面
        * */

        RestTemplate restTemplate = new RestTemplate();

        return RestResult.success();
    }

    @GetMapping("/authUser")
    private RestResult authUser(String code) {
        String appId = "wx0c739231eda04f65"; // 公众号openid
        String appSecret = "9b7435dac7c4b164a7cdb09412b6d86c"; // 公众号appSecret
        String grantType = "authorization_code";
        String requestUri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type={grantType}";
        Map<String, String> requestParams = new HashMap<String, String>() {{
            put("appid", appId);
            put("secret", appSecret);
            put("code", code);
            put("grantType", grantType);
        }};
        System.out.println("微信请求：" + requestUri);
        System.out.println("微信请求参数：" + requestParams);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUri, String.class, requestParams);
//        String responseString = restTemplate.getForObject(requestUri, String.class, requestParams);
        System.out.println("微信响应：" + responseEntity);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
            return RestResult.success().put("openid", jsonObject.getStr("openid"));
        } else {
            return RestResult.error();
        }
    }
}
